package com.bub.pay.mq.consumer.listener;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.bub.pay.mq.consumer.service.CallbackNotifyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.Map;


public class PayNotifyListener implements MessageListener {

    private final Logger log = LoggerFactory.getLogger(PayNotifyListener.class);

    @Resource
    private CallbackNotifyService callbackNotifyService;

    @Override
    public Action consume(Message message, ConsumeContext context) {
        try {
            Map<String, Object> bodyMap = JSON.parseObject(message.getBody(), Map.class);
            log.info("支付订单回调 |订单号:|{},状态:|{}|{}", bodyMap.get("orderNo"), bodyMap.get("finalState"), JSON.toJSONString(bodyMap));
            String resData = callbackNotifyService.payOrderNotify(bodyMap);
            log.info("支付订单回调,|响应:|{}", resData);
            if (!"success".equalsIgnoreCase(resData)) {
                return Action.ReconsumeLater;
            }
        } catch (Exception e) {
            log.error(String.format("支付订单回调异常 订单号:|%s 消息:|%s", message.getMsgID(), JSON.toJSONString(message)), e);
            return Action.ReconsumeLater;
        }
        return Action.CommitMessage;
    }
}
